package mwa.cs.rq.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.ZoneDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS65000Srvl
 */
public class CS65000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	private Database db;
	private int vnSiteId;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS65000Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    @SuppressWarnings({ "unchecked", "unused" })
	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("methodType");
		if (vaProcessType.equals("getDataTable")){
			getDataTable(request, response);
		}
	}

    @SuppressWarnings({ "unchecked", "unused" })
    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	this.db = new Database();
		
		JSONObject voObject = new JSONObject();
		PrintWriter voOut = response.getWriter();	
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		String vaRequestNumber = "";
		String vaStartDate = "";
		String vaToDate = "";
		String vaStatus = "";
		if(request.getParameter("sSearch_1") != null){
			if (request.getParameter("sSearch_0").equals("1")) {
				if (request.getParameter("sSearch_1").equals("")) {
					vaRequestNumber = "";
				} else {
					vaRequestNumber = request.getParameter("sSearch_1").trim();
				}
			} else {
				vaRequestNumber = "-1";
			}
			if (request.getParameter("sSearch_2").equals("")) {
				vaStartDate = "";
			} else {
				vaStartDate = JDate.saveDate(request.getParameter("sSearch_2").trim());
			}
			if (request.getParameter("sSearch_3").equals("")) {
				vaToDate = "";
			} else {
				vaToDate = JDate.saveDate(request.getParameter("sSearch_3").trim());
			}
			if (request.getParameter("sSearch_4").equals("")) {
				vaStatus = "";
			} else {
				vaStatus = request.getParameter("sSearch_4").substring(0, request.getParameter("sSearch_4").length() - 1);
			}
		}
		
		String[] vaColumnsASC = { "rq.insert_date ASC", "rq.insert_date ASC", "rq.request_number ASC",
				"rq.applicant_name ASC", "rt.request_description ASC", "rq.status ASC" };
		String[] vaColumnsDESC = { "rq.insert_date DESC", "rq.insert_date DESC", "rq.request_number DESC",
				"rq.applicant_name DESC", "rt.request_description DESC", "rq.status ASC" };

		String vaSortColumn = null;
		int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
		int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		int vnSortColumn = Integer.parseInt(request.getParameter("iSortCol_0")); // 0, 1, 2, 3
		String vaSortDirection = request.getParameter("sSortDir_0");

		if (vaSortDirection.equals("asc")) {
			vaSortColumn = vaColumnsASC[vnSortColumn];
		}
		if (vaSortDirection.equals("desc")) {
			vaSortColumn = vaColumnsDESC[vnSortColumn];
		}
		
		RequestDAO voRequestDAO = new RequestDAO(db);
		List<Map<String , Object>> voListFindAll = null;
		Map<String , Object> voMapItem = null;
		int pnEnd = vnStart + vnAmount;
		int vnTotalRecords = voRequestDAO
				.getCountAllRequestByRequestNumber(vnSiteId,
						vaRequestNumber, vaStartDate, vaToDate, vaStatus);
		int vnTotalDisplayRecords = 0;
		if (vnAmount == -1) {
			voListFindAll = voRequestDAO
					.findAllRequestByRequestNumber(vnSiteId,
							vaRequestNumber, vaStartDate, vaToDate, vaStatus, vaSortColumn);
			vnTotalDisplayRecords = vnTotalRecords;
		} else {
			voListFindAll = voRequestDAO.findRequestByRequestNumber(
					vnSiteId, vaRequestNumber, vaStartDate, vaToDate, vaStatus,
					vaSortColumn, vnStart, pnEnd);
			
			vnTotalDisplayRecords = voRequestDAO
					.getCountAllRequestByRequestNumber(vnSiteId,
							vaRequestNumber, vaStartDate, vaToDate, vaStatus);
		}
		for(int i = 0; i < voListFindAll.size() ; i++){
			voMapItem = voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i + 1);
			voColumn.add(voMapItem.get("INSERT_DATE") );
			voColumn.add(voMapItem.get("REQUEST_NUMBER"));
			voColumn.add(voMapItem.get("APPLICANT_NAME") );
			voColumn.add(voMapItem.get("REQUEST_DESCRIPTION"));
			voColumn.add(voMapItem.get("STATUS"));
			voRow.add(voColumn);
		}
		
		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
		db.close();
		voOut.print(voObject.toJSONString());
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
